<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GM工具登录</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="login-container">
        <div class="logo">GM</div>
        <h2 class="login-title">GM工具登录</h2>
        <form id="loginForm">
            <div class="input-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" placeholder="请输入用户名" required>
            </div>
            <div class="input-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" placeholder="请输入密码" required>
                <div id="errorMsg" class="error-message"></div>
            </div>
            <button type="submit" class="login-button">登录</button>
        </form>
    </div>

    <script src="js/utils.js"></script>
    <script>
        // 页面加载时检查是否已登录
        window.onload = function() {
            if (sessionStorage.getItem('gmToken')) {
                redirectToHome();
            }
        };
        
        async function handleLogin(e) {
            // 检查事件对象是否存在
            if (e && e.preventDefault) {
                e.preventDefault();
            }
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const errorMsg = document.getElementById('errorMsg');
            const loginButton = document.querySelector('.login-button');
            
            // 清空错误信息
            errorMsg.textContent = '';
            
            // 验证输入
            if (!username || username.trim() === '') {
                errorMsg.textContent = '请输入用户名';
                return false;
            }
            
            if (!password || password.trim() === '') {
                errorMsg.textContent = '请输入密码';
                return false;
            }
            
            // 禁用登录按钮防止重复提交
            loginButton.disabled = true;
            loginButton.textContent = '登录中...';
            
            try {
                // 真实API登录请求
                const response = await fetch('/gm/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: username,
                        password: password
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200 && result.data) {
                    // 保存会话信息
                    sessionStorage.setItem('gmToken', result.data);
                    sessionStorage.setItem('gmUsername', username);
                    showMessage('登录成功', 'success');
                    
                    // 延迟跳转到主页
                    setTimeout(() => {
                        redirectToHome();
                    }, 1000);
                    return false;
                } else {
                    errorMsg.textContent = result.message || '登录失败，请重试';
                    return false;
                }
            } catch (error) {
                console.error('登录请求错误:', error);
                errorMsg.textContent = '网络错误，请稍后重试';
                return false;
            } finally {
                // 恢复按钮状态
                loginButton.disabled = false;
                loginButton.textContent = '登录';
            }
        }
        
        // 绑定表单提交事件
        document.getElementById('loginForm').addEventListener('submit', handleLogin);
        
        // 监听回车键登录
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.querySelector('.login-button').click();
            }
        });
        
        function redirectToHome() {
            window.location.href = '/gm/index.html';
        }
        
        function showMessage(message, type) {
            // 简单的消息提示实现
            const msgElement = document.createElement('div');
            msgElement.className = `message ${type}`;
            msgElement.textContent = message;
            msgElement.style.position = 'fixed';
            msgElement.style.top = '50%';
            msgElement.style.left = '50%';
            msgElement.style.transform = 'translate(-50%, -50%)';
            msgElement.style.padding = '10px 20px';
            msgElement.style.backgroundColor = type === 'success' ? '#4CAF50' : '#f44336';
            msgElement.style.color = 'white';
            msgElement.style.borderRadius = '4px';
            msgElement.style.zIndex = '9999';
            document.body.appendChild(msgElement);
            
            setTimeout(() => {
                document.body.removeChild(msgElement);
            }, 2000);
        }
    </script>
</body>
</html>